﻿using Admin.ApplicationLib.Entities;
using Admin.CommonLib.Models.User;
using Ardalis.Specification;
using Swimj.Core.Extensions;

namespace Admin.ApplicationLib.Specifications
{
    public sealed class UserSpecification : Specification<UserEntity>
    {
        public UserSpecification(UserSearchRequestDto model,
            string normalizeName)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            // 忽略admin用户
            if (!normalizeName.Equals("ADMIN"))
            {
                Query.Where(i => !i.UserName.Equals("admin"));
            }

            if (!string.IsNullOrEmpty(model.UserName))
            {
                Query.Where(i => i.UserName.Contains(model.UserName));
            }

            if (!string.IsNullOrEmpty(model.Email))
            {
                Query.Where(i => i.Email.Contains(model.Email));
            }

            if (!string.IsNullOrEmpty(model.Phone))
            {
                Query.Where(i => i.PhoneNumber.Contains(model.Phone));
            }

            if (model.DataState != null)
            {
                Query.Where(i => i.DataState == model.DataState);
            }

            if (model.Page > 0)
            {
                Query.Skip((model.Page - 1) * model.Limit);
            }

            if (model.Limit > 0)
            {
                Query.Take(model.Limit);
            }

            if (!string.IsNullOrEmpty(model.Sort))
            {
                if (model.Sort.Equals("Phone"))
                {
                    model.Sort = "PhoneNumber";
                }

                Query.OrderBy(typeof(UserEntity).GetPropertyExpression<UserEntity>(model.Sort));
            }
            else
            {
                Query.OrderByDescending(i => i.CreatedOn);
            }
        }
    }
}